package com.eden.api.controller;

import com.eden.api.controller.vo.ApiResult;
import com.eden.api.utils.SortUtils;
import com.eden.common.constant.ChatConstants;
import com.eden.common.utils.StringUtils;
import com.eden.websocket.domain.Message;
import com.eden.websocket.service.IMessageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.eden.api.controller.vo.ApiResult.success;

@Slf4j
@Api("消息记录客户端")
@RestController
@RequestMapping("/api/message")
public class ApiMessageController {

    @Autowired
    private IMessageService messageService;

    //查询消息列表
    @ApiOperation("加载消息记录")
    @PostMapping("/selectMessageList")
    public ApiResult selectMessageList(@Validated @RequestBody Message message) {
        List<Message> chatLists = new ArrayList<>();
        if (StringUtils.isNotNull(message) && StringUtils.isNotEmpty((message.getToUserLoginName())) && StringUtils.isNotEmpty(message.getFromUserLoginName())) {
            //查自己发送的
            List<Message> fromChatLists = messageService.selectMessageList(message);
            if (StringUtils.isNotNull(fromChatLists) && fromChatLists.size() != 0) {
                for (Message fromChatList : fromChatLists) {
                    fromChatList.setType(ChatConstants.IS_ME_SEND);
                }
                chatLists.addAll(fromChatLists);
            }
            Message toMessage = new Message();
            toMessage.setFromUserLoginName(message.getToUserLoginName());
            toMessage.setToUserLoginName(message.getFromUserLoginName());
            //发送的对象给我发送的
            List<Message> toChatLists = messageService.selectMessageList(toMessage);
            if (StringUtils.isNotNull(toChatLists) && toChatLists.size() != 0) {
                for (Message toChatList : toChatLists) {
                    toChatList.setType(ChatConstants.NOT_ME_SEND);
                }
                chatLists.addAll(toChatLists);
            }
        }
        SortUtils sortUtils = new SortUtils();
        Collections.sort(chatLists, sortUtils);
        return success("加载消息记录成功！", chatLists);
    }

}
